<?php

$begin_time = time();

$source = $GET_source;
$column_title = array();

$source_begin = isset($_POST['begin']) ? $_POST['begin'] : 0;
$source_end = isset($_POST['count']) ? $_POST['count'] : 100;

$target_file = isset($_POST['target']) ?
        DOCUMENT_ROOT . '/public/__files/' . $_POST['target'] :
        DOCUMENT_ROOT . '/public/__files/' . $source . '.xlsx';

/*
 * Action <NEW>: Créer un nouveau exportation
 * Action <CONTINUE>: Continuer d'exporter vers des fichiers. pour l'action Continue,
 *  il retourne 0, alors ça signifie que tous les données sont exportés dans le fichier
 */
$action = isset($_POST['action']) ? $_POST['action'] : 'NEW';
$query = "";
if ($action == 'NEW') {
    $objPhpExcel = new PHPExcel;
} elseif ($action == 'CONTINUE') {
    if (file_exists($target_file)) {
        $excelReader = new PHPExcel_Reader_Excel2007;
        $objPhpExcel = $excelReader->load($target_file);
    } else {
        $objPhpExcel = new PHPExcel;
    }
}

if ($source == 'rdv') {
    $objPhpExcel->getProperties()->setTitle('Tous les rendez-vous');
    $objPhpExcel->getProperties()->setSubject('Tous les rendez-vous');
    $objPhpExcel->getProperties()->setDescription('Tous les rendez-vous');
    $objPhpExcel->getActiveSheet()->setTitle('Rdv');

    $query = "SELECT prestation.prestation_name as prestation,
        slot.title as titre,
        slot.event_type as type, 
        slot.slot_day as jour,
        slot.slot_start as debut,
        slot.slot_end as fin,
        client.nom as client_nom,
        client.prenom as client_prenom
        
        FROM msa_slotobject as slot
        INNER JOIN msa_prestationobject as prestation ON prestation.id = slot.prestation_id
        INNER JOIN msa_clientobject as client ON client.id = slot.client_id
        Where prestation.id != 0";
    if ($source_begin !== null && $source_end !== null) {
        $query .= " Limit $source_begin, $source_end";
    }

    $queryResult = Erra_Core_DatabasePdo::SELECT($query);


    $column_title = array(
        'A' => array('prestation', 'Prestation'),
        'B' => array('titre', 'Titre'),
        'C' => array('jour', 'Jour', 'filter' => function($timespam) {
                return date('d/m/Y', $timespam);
            }),
        'D' => array('debut', 'Debut', 'filter' => function($timespan) {
                return date('H:i:s', $timespan);
            }),
        'E' => array('fin', 'Fin', 'filter' => function($timespan) {
                return date('H:i:s', $timespan);
            }),
        'F' => array('client_nom', 'Nom de client'),
        'G' => array('client_prenom', 'Prenom de client')
    );
} else {

    $objPhpExcel->getProperties()->setTitle('Tous les utilisateurs');
    $objPhpExcel->getProperties()->setSubject('Tous les utilisateurs');
    $objPhpExcel->getProperties()->setDescription('Tous les utilisateurs');
    $objPhpExcel->getActiveSheet()->setTitle('utilisateurs');

    $query = "SELECT civilite, nom, prenom, email, adresse,ville,client_internet, telephone_portable, telephone_fixe, date_creation
        FROM msa_clientobject";
    if ($source_begin !== null && $source_end !== null) {
        $query .= " Limit $source_begin, $source_end";
    }

    $queryResult = Erra_Core_DatabasePdo::SELECT($query);

    $column_title = array(
        "A" => array('civilite', 'Civilité'),
        "B" => array('nom', 'Nom'),
        "C" => array('prenom', 'Prenom'),
        "D" => array('email', 'Adresse Email'),
        "E" => array('adresse', 'Adresse'),
        "F" => array('ville', 'Ville'),
        "G" => array('client_internet', 'Client d\'internet', 'filter' => function($data) {
                if ($data == 0) {
                    return 'Non';
                }
                return 'Oui';
            }
        ),
        "H" => array('telephone_portable', 'Télèphone Portable'),
        "I" => array('telephone_fixe', 'Télèphone Fixe'),
        "J" => array('date_creation', 'Date d\'inscription', 'filter' => function($timestamp) {
                return date('d/m/Y H:i:s', $timestamp);
            })
    );
}

foreach ($column_title as $colum => $desc) {
    $objPhpExcel->getActiveSheet()->getColumnDimension($colum)->setAutoSize(true);
    $objPhpExcel->getActiveSheet()->setCellValue($colum . '1', $desc[1]);
}
if ($queryResult !== false) {
    $result = array();
    $exported_count = 0;
    $index = 2 + ($source_begin !== NULL ? $source_begin : 0);

    while ($row = $queryResult->fetch(PDO::FETCH_ASSOC)) {
        foreach ($column_title as $sheet_column => $bdd_column) {
            if (isset($row[$bdd_column[0]])) {
                if (isset($bdd_column['filter'])) {
                    $row[$bdd_column[0]] = $bdd_column['filter']($row[$bdd_column[0]]);
                }
                $objPhpExcel->getActiveSheet()->setCellValue($sheet_column . $index, $row[$bdd_column[0]]);
            }
        }
        $index++;
        $exported_count++;
    }

    try {
        $result['count'] = $exported_count;

        $result['target_file'] = '/__files/' . $source . '.xlsx';

        $excelWriter = new PHPExcel_Writer_Excel2007($objPhpExcel);
        $excelWriter->save($target_file);

        $result['time_cost'] = time() - $begin_time;
        echo json_encode($result);
    } catch (\Exception $e) {
        $result['error'] = $e->getMessage();
        echo json_encode($result);
    }
}
session_write_close();

/*
header("Content-disposition: attachment; filename=" . "$source.xlsx");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Transfer-Encoding: binary");
//header("Content-Transfer-Encoding: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n");// Surtout ne pas enlever le \n
header("Content-Length: " . filesize(DOCUMENT_ROOT . "/public/__files/$source.xlsx"));
header("Pragma: no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0, public");
header("Expires: 0");
readfile(DOCUMENT_ROOT . "/public/__files/$source.xlsx");*/
